<?php
declare (strict_types = 1);

namespace App\Logic;

use App\Event\AdministratorLogsEvent;
use App\Models\Record as RecordModel;

class Record
{
    public function count(array $where = []): int
    {
        $map[] = ['delete_time', '=', 0];
        if (!empty($where['log_menu'])) $map[] = ['log_menu', 'like', '%'.$where['log_menu'].'%'];
        if (!empty($where['log_account'])) $map[] = ['log_account', 'like', '%'.$where['log_account'].'%'];
        if (!empty($where['log_ip'])) $map[] = ['log_ip', 'like', '%'.$where['log_ip'].'%'];
        if (!empty($where['create_time'])){
            $timeArr = explode(' - ', $where['create_time']);
            $startTime = $timeArr[0];
            $endTime = $timeArr[1];
            return RecordModel::where($map)->whereBetween('create_time', [$startTime, $endTime])->count();
        }
        return RecordModel::where($map)->count();
    }

    public function list(int $start, int $limit, array $where = [])
    {
        $map[] = ['delete_time', '=', 0];
        if (!empty($where['log_menu'])) $map[] = ['log_menu', 'like', '%'.$where['log_menu'].'%'];
        if (!empty($where['log_account'])) $map[] = ['log_account', 'like', '%'.$where['log_account'].'%'];
        if (!empty($where['log_ip'])) $map[] = ['log_ip', 'like', '%'.$where['log_ip'].'%'];
        if (!empty($where['create_time'])){
            $timeArr = explode(' - ', $where['create_time']);
            $startTime = $timeArr[0];
            $endTime = $timeArr[1];
            return RecordModel::select('id', 'log_account', 'log_menu', 'log_method', 'log_params', 'log_desc', 'log_ip', 'create_time')->where($map)->whereBetween('create_time', [$startTime, $endTime])->orderBy('id','desc')->offset($start)->limit($limit)->get();
        }
        return RecordModel::select('id', 'log_account', 'log_menu', 'log_method', 'log_params', 'log_desc', 'log_ip', 'create_time')->where($map)->orderBy('id','desc')->offset($start)->limit($limit)->get();
    }

    public function delete(int $id)
    {
        $model = RecordModel::find($id);
        if (empty($model)) return false;
        if ($model->delete()) {
            event(new AdministratorLogsEvent("删除后台操作日志"));
            return true;
        }
        return false;
    }

    public function remove(array $ids)
    {
        if (RecordModel::destroy($ids)) {
            event(new AdministratorLogsEvent("批量删除后台操作日志"));
            return true;
        }
        return false;
    }
}
